import {createRouter, createWebHashHistory} from 'vue-router'

import Login from '../views/login'
import Layout from "../views/layout";
import Dashboard from '../views/dashboard'
import Personal from "../views/personal";
import About from '../views/about'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import {getToken} from "@/utils/auth";

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            name: 'Login',
            path: '/login',
            component: Login,
        },
        {
            name: "Dashboard",
            path: '/',
            component: Dashboard,
            // component: Layout,
            meta: {
                isAuthenticated: true
            }
        },
        {
            path: '/Personal',
            component: Personal,
        },
        {
            path: '/about',
            component: About
        },
        {
            path: '/test',
            redirect: '/test/index',
            component: Layout,
            children: [
                {
                    path: 'index',
                    name: "TestIndex",
                    component: () => import('@/views/test/index'),
                },
                {
                    path: 'wangwu',
                    name: "TestWangwu",
                    component: () => import('@/views/test/wangwu'),
                },
                {
                    path: 'search',
                    name: "TestSearch",
                    component: () => import('@/views/test/search'),
                },
                {
                    path: 'setting',
                    name: "TestSetting",
                    component: () => import('@/views/test/setting'),
                },
            ]
        },
    ]
})

router.beforeEach((to, from, next) => {
    NProgress.start()
    console.log('beforeEach', to, from);
    // 非登录页都需要做权限验证
    if (to.name !== 'Login' && to.path.indexOf("/test") === -1) {
        const token = getToken()
        if (!token) {
            console.log('请先登录');
            next(`/login?redirect=${to.path}`)
            // next(`/login`)
            // next({
            //     name: 'Login',
            //     path: '/login',
            // })
        }

        next()
        console.log('@@beforeEach');
    } else {
        // if (to.meta.isAuthenticated) {

        // }
        next()

    }

})

router.afterEach((to, from) => {
    console.log('@afterEach', to, from);
    // finish progress bar
    NProgress.done()
})

export default router